package com.atguigu.flink.chapter07.state;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.List;

public class Flink08_State_Keyed_Map {


    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment
                .getExecutionEnvironment()
                .setParallelism(3);
        env
                .socketTextStream("hadoop162", 9999)
                .map(value -> {
                    String[] datas = value.split(",");
                    return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));

                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private MapState<Integer, Object> vcMap;
                    private AggregatingState<WaterSensor, String> vcAvgState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        vcMap = getRuntimeContext().getMapState(new MapStateDescriptor<Integer, Object>("vcMap", Integer.class, Object.class));
                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        vcMap.put(value.getVc(), new Object());

                        Iterable<Integer> keysIt = vcMap.keys();

                        List<Integer> keys = AtguiguUtil.toList(keysIt);

                        out.collect(ctx.getCurrentKey() + " " + keys);
                    }
                })
                .print();


        env.execute();
    }
}
